package cn.jjzd.info.service;

import cn.jjzd.common.pojo.PageResult;
import cn.jjzd.common.utils.DateUtils;
import cn.jjzd.info.mapper.ArticleMapper;
import cn.jjzd.info.pojo.Area;
import cn.jjzd.info.pojo.Article;
import cn.jjzd.info.pojo.Category;
import cn.jjzd.info.request.ArticleRequest;
import cn.jjzd.info.response.ArticleListResponse;
import cn.jjzd.info.response.ArticlePageResponse;
import cn.jjzd.info.response.ArticleResponse;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ArticleService {
    @Autowired
    private ArticleMapper sysArticleMapper;
    @Autowired
    private CategoryService sysCategoryService;
   /* @Autowired
    private AmqpTemplate amqpTemplate;*/

    public PageResult<ArticlePageResponse> queryArticlePage(String key, Integer page, Integer rows, String sortBy, Boolean desc, Long cid) {
        //初始化example
        Example example = new Example(Article.class);
        Example.Criteria criteria = example.createCriteria();
        //根据name模糊查询，或者根据首字母查询
        if(StringUtils.isNotBlank(key)){
            criteria.andLike("title", "%"+key+"%");//;
        }
        //根据分类查询
        if(null != cid){
            criteria.andEqualTo("categoryId", cid);//;
        }
        criteria.andEqualTo("isShow",true);
        criteria.andEqualTo("recordStatus",true);
        //添加分页条件
        PageHelper.startPage(page,rows);
        //添加排序条件
        if(StringUtils.isNotBlank(sortBy)){
            example.setOrderByClause(sortBy + " " +(desc ? "desc" : "asc"));
        }
        List<Article> articles = sysArticleMapper.selectByExample(example);
        PageInfo pageInfo = new PageInfo<>(articles);
        List<ArticlePageResponse> sysArticlePageBos = articles.stream().map(article -> {
            ArticlePageResponse sysArticlePageBo = new ArticlePageResponse();
            BeanUtils.copyProperties(article, sysArticlePageBo);
            Category category = this.sysCategoryService.queryNameById(article.getCategoryId());
            sysArticlePageBo.setCategoryName(category.getName());
            sysArticlePageBo.setCategoryFullName(sysCategoryService.queryNamesById(article.getCategoryId()));
            sysArticlePageBo.setCreateDateStr(DateUtils.dateToStr(sysArticlePageBo.getCreateDate(),"yyyy-MM-dd"));
            sysArticlePageBo.setShowStr(sysArticlePageBo.getShow() == true ? "是" : "否");
            sysArticlePageBo.setSequenceStr(sysArticlePageBo.getSequence() == true ? "是" : "否");
            return sysArticlePageBo;
        }).collect(Collectors.toList());


        //返回pageResult<>
        return new PageResult<>(pageInfo.getTotal(), sysArticlePageBos);
    }

    public void saveArticle(Article sysArticle) {
        sysArticle.setVisitNumber(0);
        sysArticle.setKeyword("");
        sysArticle.setArea("");
        sysArticle.setSequence(true);
        sysArticle.setAuthor("admin");
        sysArticle.setShow(true);
        sysArticle.setSource("后台");
        sysArticle.setSpreadDesc("");
        sysArticle.setSpreadKeyword("");
        sysArticle.setRecordStatus(true);
        sysArticle.setUpdateCount(0);
        sysArticle.setCreateDate(new Date());
        sysArticle.setUpdateDate(sysArticle.getCreateDate());
        sysArticle.setCreatorId(-1L);
        sysArticle.setUpdaterId(-1L);
        this.sysArticleMapper.insertSelective(sysArticle);
    }

   /* private void sendMsg(String type, Long id) {
        try {
            this.amqpTemplate.convertAndSend("info."+type,id);
        }catch (AmqpException e){
            e.printStackTrace();
        }
    }*/

    public List<Article> queryArticleList(Long cid) {
        Example example = new Example(Article.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("categoryId",cid);
        example.setOrderByClause("create_date desc ");
        //添加分页条件
        PageHelper.startPage(0,5);
        List<Article> articles  = sysArticleMapper.selectByExample(example);
        PageInfo pageInfo = new PageInfo<>(articles);
        List<Article> items = new PageResult<>(pageInfo.getTotal(), articles).getItems();
        return  items;
    }

    public List<ArticleResponse> queryArticBoList(List<Long> ids){
        List<ArticleResponse> articleBos = new ArrayList<>();
        for (Long id : ids) {
            List<Article> articles = queryArticleList(id);
            List<ArticleListResponse> articleListBos = articles.stream().map(article -> {
                ArticleListResponse sysArticleBo = new ArticleListResponse();
                sysArticleBo.setName(article.getTitle());
                sysArticleBo.setId(article.getId());
                sysArticleBo.setMoreUrl("");
                sysArticleBo.setTime("["+DateFormatUtils.format(article.getCreateDate(), "yyyy-MM-dd")+"]");
                return sysArticleBo;
            }).collect(Collectors.toList());

            ArticleResponse sysArticleBo = new ArticleResponse();
            Category category = this.sysCategoryService.queryNameById(id);
            sysArticleBo.setName(category.getName());
            sysArticleBo.setMoreUrl(category.getUrl());
            sysArticleBo.setId(category.getId());
            sysArticleBo.setContentList(articleListBos);

            articleBos.add(sysArticleBo);
        }
        return articleBos;
    }


    public List<ArticleResponse> queryArticBoList(Long cid){
        List<Article> articles = queryArticleList(cid);
        List<ArticleResponse> articleBos = new ArrayList<>();
        List<ArticleListResponse> articleListBos = articles.stream().map(article -> {
            ArticleListResponse sysArticleBo = new ArticleListResponse();
            sysArticleBo.setName(article.getTitle());
            sysArticleBo.setMoreUrl("");
            sysArticleBo.setTime("["+DateFormatUtils.format(article.getCreateDate(), "yyyy-MM-dd")+"]");
            return sysArticleBo;
        }).collect(Collectors.toList());

        ArticleResponse sysArticleBo = new ArticleResponse();
        Category category = this.sysCategoryService.queryNameById(cid);
        sysArticleBo.setName(category.getName());
        sysArticleBo.setMoreUrl("");
        sysArticleBo.setContentList(articleListBos);

        articleBos.add(sysArticleBo);
        return articleBos;
    }

    public Article queryById(Long id) {
        return sysArticleMapper.selectByPrimaryKey(id);
    }

    public PageResult<ArticleListResponse> queryArticleMorePage(ArticleRequest request) {
        //初始化example
        Example example = new Example(Article.class);
        Example.Criteria criteria = example.createCriteria();
        //根据name模糊查询，或者根据首字母查询
        /*if(StringUtils.isNotBlank(key)){
            criteria.andLike("title", "%"+key+"%");//;
        }*/
        //根据分类查询
        if(null != request.getCid()){
            criteria.andEqualTo("categoryId", request.getCid());//;
        }
        //添加分页条件
        PageHelper.startPage(request.getPage(),request.getSize());
        //添加排序条件
        /*if(StringUtils.isNotBlank(sortBy)){
            example.setOrderByClause(sortBy + " " +(desc ? "desc" : "asc"));
        }*/
        List<Article> articles = sysArticleMapper.selectByExample(example);
        PageInfo<Article> pageInfo = new PageInfo<>(articles);
        List<ArticleListResponse> sysArticlePageBos = articles.stream().map(article -> {
            ArticleListResponse sysArticlePageBo = new ArticleListResponse();
            BeanUtils.copyProperties(article, sysArticlePageBo);
            sysArticlePageBo.setTitle(article.getTitle());
            sysArticlePageBo.setContent(article.getContent());
            sysArticlePageBo.setUrl(article.getImagePath());
            sysArticlePageBo.setMoreUrl("");
            return sysArticlePageBo;
        }).collect(Collectors.toList());


        //返回pageResult<>
        return new PageResult<>(pageInfo.getTotal(),pageInfo.getPages(), sysArticlePageBos);
    }

    public void deleteById(Long id) {
        Article article = sysArticleMapper.selectByPrimaryKey(id);
        article.setRecordStatus(false);
        article.setShow(false);
        sysArticleMapper.updateByPrimaryKey(article);
    }

    public void updateArticle(Article articled) {
        if(null != articled && null != articled.getId()){
            Article orginArticle = sysArticleMapper.selectByPrimaryKey(articled.getId());
            orginArticle.setTitle(articled.getTitle());
            orginArticle.setCategoryId(articled.getCategoryId());
            orginArticle.setDescription(articled.getDescription());
            orginArticle.setImagePath(articled.getImagePath());
            orginArticle.setUpdateCount(articled.getUpdateCount()+1);
            sysArticleMapper.updateByPrimaryKey(orginArticle);
        }
    }
}
